<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>写日记</title>
        <base th:href="${#request.getContextPath()}+'/'">
        <!--bootstrap.min.css-->
        <link rel="stylesheet" th:href="@{/bootstrap/css/bootstrap.min.css}">
        <link rel="stylesheet" th:href="@{/layer/layui.css}">
        <link rel="stylesheet" th:href="@{/bootstrap/font-awesome/css/font-awesome.min.css}">
        <link rel="stylesheet" th:href="@{/bootstrap/css/menu/write_diary.css}">
    </head>
    <body>
        <div class="container">
            <form id="article" class="form-horizontal" style="margin-top: 15px;">
                <input type="hidden" name="articleKey"/>
                <div class="col-md-12">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">标题：</label>
                        <div class="col-sm-10">
                            <input type="text" autocomplete="off" name="title" class="form-control" placeholder="请输入日记标题">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">是否公开：</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" value="0" name="publicity" checked="">不公开
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="publicity" value="1">公开
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">标签：</label>
                        <div class="col-sm-10">
                            <!--<input type="hidden" class="form-control" name="tags" placeholder="请输入/选择分类标签">-->
                            <div class="wrap">
                                <div class="label-selected">
                                    <a href="javascript:void(0);"
                                       class="layui-btn layui-btn-normal layui-btn-sm show-labelitem"
                                       style="float: right; margin: 4px; display: block;line-height: 30px;">展开标签库
                                    </a>
                                    <a href="javascript:void(0);"
                                       class="layui-btn layui-btn-normal layui-btn-sm hide-labelitem"
                                       style="float: right; margin: 4px; display: none;line-height: 30px;">收起标签库
                                    </a>
                                    <a href="javascript:void(0);"
                                       class="layui-btn layui-btn-normal layui-btn-sm add-labelitem"
                                       style="float: right; margin: 4px; display: block;line-height: 30px;">添加新标签
                                    </a>
                                    <input type="hidden" name="tags">
                                </div>
                                <div class="layui-col-md12" id="labelItem">
                                    <!--标签库-->
                                    <div class="label-item">
                                        <a href="javascript:void(0);" class="replacelable"
                                           style="position: absolute;right:1rem;bottom:.75rem;color: #1994dc"
                                           onselectstart="return false">换一批
                                        </a>
                                    </div>
                                </div>
                                <!--<a href="javascript:void(0);" class="layui-btn" id="cell">获取</a>-->
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">日记内容：</label>
                        <div class="col-sm-10">
                            <div id="editor"></div>
                            <!--<textarea class="form-control" name="content" placeholder="请输入文本"></textarea>-->
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="button" onclick="submitFrom()" class="btn btn-primary"><i
                                    class="fa fa-check pdr5" aria-hidden="true"></i>发布
                            </button>
                            <button type="button" onclick="cancel()" class="btn btn-success">
                                <i class="fa fa-times pdr5"
                                   aria-hidden="true"></i>
                                取消
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </body>
    <script type="text/javascript" th:src="@{https://lib.baomitu.com/wangEditor/3.1.1/wangEditor.min.js}"></script>
    <script type="text/javascript" th:src="@{https://lib.baomitu.com/jquery/3.5.0/jquery.min.js}"></script>
    <script type="text/javascript" th:src="@{https://cdn.bootcdn.net/ajax/libs/layer/3.1.1/layer.min.js}"></script>
    <script type="text/javascript" th:src="@{/bootstrap/js/AjaxUtil.js}"></script>
    <script type="text/javascript" th:src="@{/bootstrap/js/JSONUtil.js}"></script>
    <!--bootstrap.min.js-->
    <script type="text/javascript" th:src="@{/bootstrap/js/bootstrap.min.js}"></script>
    <script>
        let isEdit = false, editor;

        function init(data) {
            let E = window.wangEditor;
            editor = new E('#editor');
            // 关闭粘贴样式的过滤
            editor.customConfig.pasteFilterStyle = false;
            // 忽略粘贴内容中的图片
            editor.customConfig.pasteIgnoreImg = true;
            // base64 保存图片
            editor.customConfig.uploadImgShowBase64 = true;
            editor.create();

            if (Object.keys(data).length > 0) {
                isEdit = true;
                $("input[name='articleKey']").val(data.articleKey);
                $("input[name='title']").val(data.title);
                editor.txt.html(data.content);
                // $("textarea[name='content']").val(data.content);
                $("input[name='publicity']").val(data.publicity);
                let tags = data.tagList;
                if (tags && tags.length > 0) {
                    for (let i = 0; i < tags.length; i++) {
                        let v = tags[i];
                        addTag(v.tagKey, v.name);
                    }
                    switchTag(32, tags);
                }
            } else {
                switchTag(32, null);
            }
        }

        /*选择与取消*/
        $(".show-labelitem").on("click", function () {
            $(this).hide();
            $(".hide-labelitem").show();
            $("#labelItem").show();
        });
        $(".hide-labelitem").on("click", function () {
            $(this).hide();
            $(".show-labelitem").show();
            $("#labelItem").hide();
        });

        /*添加自定义标签*/
        $(".add-labelitem").on("click", function () {
            layer.prompt({title: '添加你的自定义标签，并确认', formType: 2}, function (text, index) {
                let url = 'tag/addTag';
                AjaxPost(url, {name: text}, function () {
                }, function (result) {
                    if (result.code === 200) {
                        addTag(result.data.tagKey, text);
                        layer.close(index);
                    } else {
                        layer.msg(result.message, {icon: 0});
                    }
                });
            });
        });
        /*点击添加标签*/
        $(".label-item").on("click", "li", function () {
            let id = $(this).attr("data");
            let text = $(this).children("span").html();
            if ($(this).hasClass("selected")) {
                return false;
            } else {
                addTag(id, text);
                $(this).addClass("selected");
            }
        });
        let val = "";
        $(".label-selected").on("click", "li", function () {
            let id = $(this).attr("data");
            val = '';
            $(this).remove();
            for (let i = 0; i < $(".label-selected").children("li").length; i++) {
                val += $(".label-selected").children("li").eq(i).attr("data") + ',';
            }
            $("input[name='tags']").val(val);
            $(".label-item").find("li[data='" + id + "']").removeClass("selected");
        });

        /**
         * 添加标签实现
         * @param key 标签ID
         * @param value 标签值
         */
        function addTag(key, value) {
            let labelHTML = '<li data="' + key + '"><i class="menu-item-icon fa fa-fw fa-tags" style="margin-right: 5px;">' +
                '</i>' + value + '</li>';
            if ($(".label-selected").children("li").length >= 10) {
                layer.msg("最多可以选择10个哦");
                return false;
            }
            $(".label-selected").append(labelHTML);
            val = '';
            for (let i = 0; i < $(".label-selected").children("li").length; i++) {
                val += $(".label-selected").children("li").eq(i).attr("data") + ',';
            }
            $("input[name='tags']").val(val);
        }


        //点击更换标签
        let limit = 0;
        $(".replacelable").on("click", function () {
            limit += 32;
            switchTag(limit);
        });

        /**
         * 换一换啦
         * @param limit
         * @param exist
         */
        function switchTag(limit, exist) {
            layer.load(1);
            let url = 'tag/switchTags';
            $.ajax({
                url: url,
                type: "post",
                datatype: "json",
                data: {
                    labelLimit: limit
                },
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code === 200) {
                        let data = result.data;
                        //删除原先所有，本来想让数据表随机搜索的，想着有点mmp，就没搞，用的是limit
                        $(".label-item").find("li").remove();
                        let html = '', has = [];
                        if (data.length > 0) {
                            let selected = $("input[name='tags']").val();
                            if (selected !== "") {
                                has = selected.substr(0, selected.length - 1).split(',');
                            }
                            for (let i in data) {
                                let key = data[i].tagKey + "";
                                html += '<li ' + (has.indexOf(key) !== -1 ? 'class="selected"' : '') + ' data="' +
                                    key + '"><i class="menu-item-icon fa fa-fw fa-tags" style="margin-right: 5px;">' +
                                    '</i><span>' + data[i].name + '</span></li>';//拼接标签
                            }
                        }
                        $(".label-item").append(html);//追加至文档
                    }
                },
                error: function () {
                    layer.closeAll('loading');
                    layer.msg("错误~~~");
                }
            })
        }

        /**
         * 提交表单
         */
        function submitFrom() {
            let data = $('#article').serialize();
            //序列化获得表单数据，结果为：user_id=12&user_name=John&user_age=20
            let formData = JSONUtil.serializeFormToJson(data);
            formData['content'] = editor.txt.html();
            let url = "article/addOrUpdateArticle";
            ajaxPost(url, formData, function () {
                layer.load(1);
            }, function (result) {
                if (result.code === 200) {
                    layer.closeAll('loading');
                    if (isEdit) {
                        formData['tagList'] = getSelectedTag();
                        parent.editSuccessCallback(formData);
                    }
                    layer.msg('操作成功', {icon: 1, time: 800}, function () {
                        cancel();
                    });
                } else {
                    layer.closeAll('loading');
                    layer.msg(result.message, {icon: 0});
                }
            }, function () {
                layer.closeAll('loading');
                layer.msg('服务器好像出了问题, 请稍后重试', {icon: 0});
            });
        }

        /**
         * 获取选择的标签
         * @returns {Array}
         */
        function getSelectedTag() {
            let result = [];
            let $li = $(".label-selected").children("li");
            if ($li.length > 0) {
                for (let i = 0; i < $li.length; i++) {
                    let $v = $li.eq(i), obj = {};
                    obj['tagKey'] = $v.attr("data");
                    obj['name'] = $v.text();
                    result.push(obj);
                }
            }
            return result;
        }

        function cancel() {
            let index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            parent.layer.close(index); //再执行关闭
        }


    </script>
</html>